from rest_framework.response import Response
from rest_framework import serializers
from django.utils import timezone


class ApiResponseMixin:
    """统一API响应格式混入类 - 用于自定义Action"""

    def success_response(self, data=None, message="操作成功", code=200):
        response_data = {
            'code': code, 'message': message, 'data': data,
            'timestamp': timezone.now().isoformat()
        }
        return Response(response_data, status=code)

    def error_response(self, message="操作失败", errors=None, code=400):
        response_data = {
            'code': code, 'message': message,
            'timestamp': timezone.now().isoformat()
        }
        if errors:
            response_data['errors'] = errors
        return Response(response_data, status=code)


def create_success_response_serializer(data_serializer, default_message="操作成功", suffix=""):
    """创建成功响应序列化器的辅助函数

    Args:
        data_serializer: 数据序列化器类或已实例化的序列化器(如many=True)
        default_message: 默认响应消息
        suffix: 序列化器名称后缀，用于区分不同的响应类型
    """
    class SuccessResponseSerializer(serializers.Serializer):
        code = serializers.IntegerField(default=200, help_text="状态码")
        message = serializers.CharField(default=default_message, help_text="响应消息")
        # 🔑 关键：支持传入序列化器类或已实例化的序列化器(如many=True)
        # 检查是否是已实例化的序列化器（包括ListSerializer）
        if data_serializer is None:
            # 没有数据序列化器，使用字典字段
            data = serializers.DictField(help_text="响应数据", required=False)
        elif hasattr(data_serializer, 'child'):
            # 已实例化的序列化器，直接使用
            data = data_serializer
        else:
            # 序列化器类，需要实例化
            data = data_serializer(help_text="响应数据")
        timestamp = serializers.DateTimeField(help_text="响应时间戳")

        class Meta:
            # 🔑 关键：获取序列化器类名，处理已实例化的情况
            if data_serializer is None:
                ref_name = f"GenericSuccessResponse{suffix}"
            elif hasattr(data_serializer, 'child'):
                # ListSerializer情况，获取child的类名
                ref_name = f"{data_serializer.child.__class__.__name__}ListSuccessResponse{suffix}"
            else:
                # 普通序列化器类
                ref_name = f"{data_serializer.__name__}SuccessResponse{suffix}"

    return SuccessResponseSerializer


class ErrorResponseSerializer(serializers.Serializer):
    code = serializers.IntegerField()
    message = serializers.CharField()
    errors = serializers.DictField(required=False)
    timestamp = serializers.DateTimeField()


# 继承错误响应序列化器
class ValidationErrorResponseSerializer(ErrorResponseSerializer): 
    pass

class UnauthorizedErrorResponseSerializer(ErrorResponseSerializer): 
    pass

class ForbiddenErrorResponseSerializer(ErrorResponseSerializer): 
    pass

class NotFoundErrorResponseSerializer(ErrorResponseSerializer): 
    pass

class ConflictErrorResponseSerializer(ErrorResponseSerializer):
    pass


class ConfigurableActionMixin:
    """
    配置式Action混入类 - 提供类似ViewSet的搜索、过滤、排序配置

    支持的URL参数格式：
    - 搜索: ?search=关键词
    - 过滤: ?字段名=值 或 ?字段名__查询类型=值
    - 排序: ?ordering=字段名 或 ?ordering=-字段名 (降序)
    - 分页: ?page=页码&page_size=每页数量
    """

    def apply_action_filters(self, queryset, request, action_config=None):
        """应用配置式的搜索、过滤、排序"""
        if not action_config:
            return queryset

        # 1. 应用搜索
        search_fields = action_config.get('search_fields', [])
        if search_fields:
            queryset = self._apply_search(queryset, request, search_fields)

        # 2. 应用过滤 - 支持filterset_fields（ViewSet标准格式）
        filter_fields = action_config.get('filterset_fields', {})
        if filter_fields:
            queryset = self._apply_filters(queryset, request, filter_fields)

        # 3. 应用排序 - 支持ordering（ViewSet标准格式）
        ordering_fields = action_config.get('ordering_fields', [])
        default_ordering = action_config.get('ordering', [])
        if ordering_fields or default_ordering:
            queryset = self._apply_ordering(queryset, request, ordering_fields, default_ordering)

        return queryset

    def _apply_search(self, queryset, request, search_fields):
        """应用搜索功能"""
        query_params = getattr(request, 'query_params', getattr(request, 'GET', {}))
        search = query_params.get('search', '').strip()
        if not search or not search_fields:
            return queryset

        # 构建搜索查询
        from django.db.models import Q
        search_queries = Q()
        for field in search_fields:
            search_queries |= Q(**{f"{field}__icontains": search})

        return queryset.filter(search_queries)

    def _apply_filters(self, queryset, request, filter_fields):
        """应用过滤功能 - 支持ViewSet的filterset_fields格式"""
        query_params = getattr(request, 'query_params', getattr(request, 'GET', {}))

        # 如果是列表格式，转换为字典格式
        if isinstance(filter_fields, list):
            filter_fields = {field: field for field in filter_fields}

        for param_name, field_config in filter_fields.items():
            if isinstance(field_config, str):
                # 简单字典格式：{'param_name': 'field_name'}
                param_value = query_params.get(param_name)
                if param_value is not None:
                    # 智能类型转换
                    if param_value.lower() in ('true', 'false'):
                        param_value = param_value.lower() == 'true'
                    elif param_value.isdigit():
                        param_value = int(param_value)
                    queryset = queryset.filter(**{field_config: param_value})

        return queryset

    def _apply_ordering(self, queryset, request, ordering_fields, default_ordering):
        """应用排序功能"""
        query_params = getattr(request, 'query_params', getattr(request, 'GET', {}))
        ordering = query_params.get('ordering', '').strip()

        if ordering and ordering_fields:
            # 验证排序字段是否允许
            ordering_list = [o.strip() for o in ordering.split(',') if o.strip()]
            valid_orderings = []

            for order in ordering_list:
                field_name = order.lstrip('-')
                if field_name in ordering_fields:
                    valid_orderings.append(order)

            if valid_orderings:
                return queryset.order_by(*valid_orderings)

        # 应用默认排序
        if default_ordering:
            return queryset.order_by(*default_ordering)

        return queryset

    def get_action_config(self, action_name):
        """获取Action配置"""
        action_configs = getattr(self, 'action_configs', {})
        return action_configs.get(action_name, {})

    def paginate_queryset_if_configured(self, queryset, action_name):
        """根据Action配置决定是否分页"""
        action_config = self.get_action_config(action_name)
        use_pagination = action_config.get('use_pagination', False)

        if use_pagination:
            # 使用ViewSet的分页器
            if hasattr(self, 'paginate_queryset'):
                return self.paginate_queryset(queryset)
            else:
                return None
        else:
            # 返回特殊标记表示强制不分页
            return 'NO_PAGINATION'
